<template>
  <a-modal
    :visible="visible"
    :confirmLoading="confirmLoading"
    title="流程设计"
    @cancel="handleCancel"
    @ok="handleOk"
    :destroyOnClose="true"
    width="100%"
    cancelText="关闭">
    <div class="containerBox">
      <div id="canvas" style="width: 90%; height: 70vh"></div>
      <div id="js-properties-panel" class="panel"></div>
      <UserSelectModal ref="userSelectModal" @selectUser="selectUser"></UserSelectModal>
      <listener-select-modal ref="listenerSelectModal" @selectListener="selectListener"></listener-select-modal>
      <UserGroupSelectModal ref="userGroupSelectModal" @selectGroup="selectUser"></UserGroupSelectModal>
    </div>
  </a-modal>
</template>
<script>

  import BpmnModeler from 'bpmn-js/lib/Modeler'
  import 'bpmn-js/dist/assets/diagram-js.css' // 左边工具栏以及编辑节点的样式
  import 'bpmn-js/dist/assets/bpmn-font/css/bpmn.css'
  import 'bpmn-js/dist/assets/bpmn-font/css/bpmn-codes.css'
  import 'bpmn-js/dist/assets/bpmn-font/css/bpmn-embedded.css'
  import 'bpmn-js-properties-panel/dist/assets/bpmn-js-properties-panel.css'
  import propertiesPanelModule from 'bpmn-js-properties-panel'
  import propertiesProviderModule from 'bpmn-js-properties-panel/lib/provider/camunda'
  import camundaModdleDescriptor from 'camunda-bpmn-moddle/resources/camunda'
  import minimapModule from 'diagram-js-minimap' //导入小地图
  import '@/assets/less/minimap.css'//自定义小地图样式
  import translate from '@/utils/flow/translate.js'
  import {getAction, postAction} from '@/api/manage'
  import UserSelectModal from '../components/UserSelectModal'
  import ListenerSelectModal from '../components/ListenerSelectModal'
  import UserGroupSelectModal from '../components/UserGroupSelectModal'

  export default {
    name: 'ExtActProcessModal',
    components: {UserGroupSelectModal, UserSelectModal, ListenerSelectModal},
    data() {
      return {
        bpmnModeler: null,
        containerEl: null,
        visible: false,
        confirmLoading: false,
        processId: '',
        processName: '',
        userInputId: '',
        model: {},
        shape: {},
        url: {
          saveBpmXml: '/process/extActProcess/edit',
          queryById: '/process/extActProcess/queryById',
        }
      }
    },
    created() {

    },
    methods: {
      rejectEventListener() {
        let eventBus = this.bpmnModeler.get('eventBus')
        let elementRegistry = this.bpmnModeler.get('elementRegistry')
        let eventTypes = ['element.click', 'element.changed']

        eventBus.on('element.click', (e) => {
          if (!e || !e.element) {
            console.log('无效的e:', +e)
            return
          }
          let shape = e.element ? elementRegistry.get(e.element.id) : e.shape
          console.debug(shape.type+e.element.id);
          if (shape.type == 'bpmn:UserTask') {
            let input1 = document.getElementById('camunda-assignee')
            input1.addEventListener('click', () => {
              this.shape = shape;
              this.userInputId = "camunda-assignee";
              this.$refs.userSelectModal.show(false);
            });
            let input2 = document.getElementById('camunda-candidateUsers')
            input2.addEventListener('click', () => {
              this.shape = shape;
              this.userInputId = "camunda-candidateUsers";
              this.$refs.userSelectModal.show(true);
            });
            let input3 = document.getElementById('camunda-candidateGroups')
            input3.addEventListener('click', () => {
              this.shape = shape;
              this.userInputId = "camunda-candidateGroups";
              this.$refs.userGroupSelectModal.show();
            });
            let input4 = document.getElementById('camunda-listener-value')
            input4.addEventListener('click', () => {
              this.shape = shape;
              let selectSelect = document.getElementById("camunda-listener-type-select").value;
              this.userInputId = "camunda-listener-value";
              this.$refs.listenerSelectModal.show();
            });
          } else if (shape.type == 'bpmn:SequenceFlow' || shape.type == 'bpmn:Process') {
            let input1 = document.getElementById('camunda-listener-value')
            input1.addEventListener('click', () => {
              this.shape = shape;
              let selectSelect = document.getElementById("camunda-listener-type-select").value;
              this.userInputId = "camunda-listener-value";
              this.$refs.listenerSelectModal.show();
            });
          }
        })
      },
      initModeler(processXml) {
        this.containerEl = document.getElementById('canvas')
        this.bpmnModeler = new BpmnModeler({
          container: this.containerEl,
          propertiesPanel: {
            parent: '#js-properties-panel'
          },
          additionalModules: [
            propertiesProviderModule,
            propertiesPanelModule,
            minimapModule,
            {
              translate: ['value', translate]
              // 禁用滚轮滚动
              // zoomScroll: ["value", ""],
              // // 禁止拖动线
              // bendpoints: ["value", ""],
              // // 禁用左侧面板
              // paletteProvider: ["value", ""],
              // // 禁止点击节点出现contextPad
              // contextPadProvider: ["value", ""],
              // // 禁止双击节点出现label编辑框
              // labelEditingProvider: ["value", ""]
            }
          ],
          moddleExtensions: {
            camunda: camundaModdleDescriptor
          }
        })
        var canvas = this.bpmnModeler.get('canvas')
        // 设置画布背景色
        canvas._container.style.backgroundColor = '#f2f2f2'
        this.createNewDiagram(processXml)
      }
      ,
      async getProcessXML(processId) {
        return await getAction(this.url.queryById, {id: processId})
      }
      ,
      async open(processId,processName) {
        this.visible = true
        this.processId = processId
        this.processName = processName;
        let {success, result, message} = await this.getProcessXML(processId)
        let showXml = ''
        if (success) {
          this.model = result;
          if (result.processXmlStr) {
            showXml = result.processXmlStr
          }
        }
        this.$nextTick(() => {
          this.initModeler(showXml)
          this.rejectEventListener()
        })
      }
      ,
      createNewDiagram(processXml) {
        if (processXml) {
          // 将字符串转换成图显示出来
          this.bpmnModeler.importXML(processXml, err => {
            if (err) {
              // console.error(err)
            } else {
              // 这里是成功之后的回调, 可以在这里做一系列事情
              this.success(processXml)
            }
          })
        } else {
          this.bpmnModeler.createDiagram(() => {
            this.success(processXml);
          });
        }
      }
      ,
      success(processXml) {
        let modeling = this.bpmnModeler.get('modeling')
        let processId = document.getElementById("camunda-id").value;
        let elementRegistry = this.bpmnModeler.get('elementRegistry');
        let shape  = elementRegistry.get(processId);
        let props = {};
        props.isExecutable = true;
        props.name = this.processName
        modeling.updateModdleProperties(shape, shape.businessObject,props);
        if(!processXml){
          processId = "process"+new Date().getTime();
          modeling.updateProperties(shape,{id: processId});
        }

      }
      ,
      close() {
        this.$emit('close')
        this.visible = false
      },
      validateProcessIdRepeated(){


      },
      handleOk() {
        const that = this
        let flowIdEL = document.getElementById("camunda-id");
        this.bpmnModeler.saveXML().then(content => {
          that.confirmLoading = true
          postAction(that.url.saveBpmXml, {id: that.processId,
            flowId: flowIdEL.value,
            processXmlStr: content.xml}).then((res) => {
            if (res.success) {
              that.$message.success(res.message)
              that.$emit('ok')
              that.close();
            } else {
              that.$message.warn(res.message)
            }
          }).finally(() => {
            that.confirmLoading = false
          })
        })
      },
      selectUser(auditUsers) {
        let modeling = this.bpmnModeler.get('modeling');
        let userModel = {};
        this.userInputId = this.userInputId.replace("-", ":");
        userModel[this.userInputId] = auditUsers;
        modeling.updateProperties(this.shape, userModel);
      },
      selectListener(listener) {
        let modeling = this.bpmnModeler.get('modeling');
        let extensionElements = this.shape.businessObject.extensionElements;
        extensionElements.values[0].class = listener
        modeling.updateProperties(this.shape, {
          extensionElements
        });
      },
      handleCancel() {
        this.close()
      },
    }
  }
</script>

<style>
  .containerBox {
    height: 100%;
    overflow: hidden;
  }

  .containerBox #container {
    height: 100%;
    border: 1px solid rgb(121, 121, 121);
  }

  .bpp-properties-panel [type=text] {
    box-sizing: border-box;
  }

  .panel {
    width: 400px;
    position: absolute;
    top: 1px;
    right: 1px;
    height: 90%;
    overflow: auto;
  }

  /* 右下角logo */
  .bjs-powered-by {
    display: none;
  }
</style>

